package han.study.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil2 {
    public static DataSource source;
    static{
        try{
            Properties props = new Properties();
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            props.load(is);
            source = DruidDataSourceFactory.createDataSource(props);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 获取连接公共方法
     * @return Connection con
     * @throws Exception
     */
    public static Connection getConnection() throws Exception{
        Connection conn = source.getConnection();
        return conn;
    }

    /**
     * 关闭资源公共方法
     * @param conn
     * @param ps
     */
    public static void closeResource(Connection conn, Statement ps){
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭资源重载方法
     * @param conn
     * @param ps
     * @param rs
     */
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
        if(conn != null){
            try{
                conn.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(ps != null){
            try{
                ps.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(rs != null){
            try{
                ps.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
